package com.typing.aop;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 使用AspectJ添加log4j日志
 */

@Aspect
@Component
public class LogAop {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	ThreadLocal<Long> startTime = new ThreadLocal<>();

	@Before(value = "execution(* com.typing.controller.*.*(..))")
	public void logBefore(JoinPoint jp) throws Throwable {

		startTime.set(System.currentTimeMillis());
		// 接收到请求，记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (attributes == null) {
			return;
		}

		HttpServletRequest request = attributes.getRequest();
		// 记录下请求内容
		//	URL:请求的地址
		logger.info("URL :{}", request.getRequestURL().toString());
		//	HTTP_METHOD:请求方式
		logger.info("HTTP_METHOD :{}", request.getMethod());
		//	IP:请求的ip地址
		logger.info("IP :{}", request.getRemoteAddr());
		//	CLASS_METHOD:请求的方法名
		logger.info("CLASS_METHOD : {}", jp.getSignature().getDeclaringTypeName() + "." + jp.getSignature().getName());
		//	ARGS:请求的方法的入参
		logger.info("ARGS : {}", Arrays.toString(jp.getArgs()));

	}

	@AfterReturning(returning = "ret", value = "execution(* com.typing.controller.*.*(..))")
	public void logAfter(Object ret) {
		//	RESPONSE:请求方法返回值
		logger.info("RESPONSE :{} ", ret);
		//	SPEND TIME:花费毫秒数
		logger.info("SPEND TIME :{} ", (System.currentTimeMillis() - startTime.get()));
	}
}
